import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {formatMessage} from './intl';
import {Cascader, Spin} from 'antd';
import stringify from 'Shared/utils/stringify';
import styles from '../common/RegionSelect.css';

const basePath = fetch.basePath || '';

/* eslint-disable eqeqeq */
class ItemTypeSelect extends PureComponent {
    state = {
        options: [],
        hasSelected: false,
        popupVisible: false,
        hasGetInitData: false
    }
    loadData = selectedOptions => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        this.getRegions(targetOption.value)
            .then(data => {
                if(data && data.length > 0)
                    targetOption.children = data.map(p => ({
                        label: p.name,
                        value: p.id,
                        isLeaf: true
                    }));
                else
                    targetOption.isLeaf = true;

                targetOption.loading = false;

                this.setState({
                    options: [...this.state.options]
                });
            });
    }
    getRegions = parentId => {
        const condition = stringify({
            parentId
        });
        return fetch(`${basePath}/afterSales/api/v1/marketingActivityDeclares/itemType?${condition}`)
            .then(res => {
                if(res.ok)
                    return res.json().then(data => {
                        const responseData = data && data.payload && data.payload ? data.payload : [];
                        return responseData;
                    });
                return [];
            });
    }

    getDefaultRegionOption = () => {
        const option = [];
        if(this.props.defaultOption) {
            const {marketingActivityItemCategoryL1Name, marketingActivityItemCategoryL1Id,
                marketingActivityItemCategoryL2Name, marketingActivityItemCategoryL2Id} = this.props.defaultOption;
            if(marketingActivityItemCategoryL1Name && marketingActivityItemCategoryL1Id) {
                option[0] = {
                    label: marketingActivityItemCategoryL1Name,
                    value: marketingActivityItemCategoryL1Id
                };
                if(marketingActivityItemCategoryL2Name && marketingActivityItemCategoryL2Id)
                    option[0].children = [{
                        label: marketingActivityItemCategoryL2Name,
                        value: marketingActivityItemCategoryL2Id
                    }];
            }
        }
        return option;
    }
    onChange = value => {
        this.props.onChange(value, this.props.name);
        this.setState({hasSelected: true});
    }
    onFocus = () => {
        this.setState({popupVisible: true});
        if(this.state.hasGetInitData)
            return;

        // 添加loading效果
        this.setState({
            options: [{
                label: <Spin size="small" />,
                value: 'ANT_CASCADER_NOT_FOUND',
                disabled: true,
            }]
        });
        this.getRegions().then(data => {
            const tmp = data.map(p => ({
                label: p.name,
                value: p.id,
                isLeaf: false
            }));
            this.setState({
                options: tmp,
                hasGetInitData: true
            });
        });
    }
    onPopupVisibleChange = visible => {
        this.setState({popupVisible: visible});
    }
    render() {
        const options = !this.state.popupVisible && !this.state.hasSelected && this.props.defaultOption
            ? this.getDefaultRegionOption()
            : this.state.options;

        return (
            <Cascader
                className={styles.select}
                placeholder={formatMessage({
                    id: 'regionSelect.selectPlaceholder',
                    defaultMessage: '请选择'
                })}
                options={options}
                getPopupContainer={trigger => trigger.parentNode}
                value={this.props.value}
                onClick={this.onFocus}
                loadData={this.loadData}
                onChange={this.onChange}
                popupVisible={this.state.popupVisible}
                disabled={this.props.disabled}
                onPopupVisibleChange={this.onPopupVisibleChange}
                changeOnSelect={this.props.changeOnSelect} />
        );
    }
}

ItemTypeSelect.propTypes = {
    name: PropTypes.string.isRequired,
    value: PropTypes.array.isRequired,
    /**
     * @param value
     * @param name
     */
    onChange: PropTypes.func.isRequired,
    changeOnSelect: PropTypes.bool,
    defaultOption: PropTypes.object,
    disabled: PropTypes.bool
};

ItemTypeSelect.defaultProps = {
    disabled: false,
    changeOnSelect: true
};
export default ItemTypeSelect;
